class Solution {//leetcode315——计算右侧小于当前元素的个数
private:
    void merge_sort(vector<int>& nums,int begin,int end){
        if(begin>=end) return;
        //分治
        int mid=(begin+end)/2;
        merge_sort(nums,begin,mid);
        merge_sort(nums,mid+1,end);
        //归并
        int cur1=begin,cur2=mid+1,i=begin;
        while(cur1<=mid&&cur2<=end){
            if(nums[cur1]<=nums[cur2]){
                tmp[i++]=make_pair(nums[cur2],index[cur2]);
                cur2++;
            }
            else {//if nums[cur1]>nums[cur2]
                ret[index[cur1]]+=end-cur2+1;
                tmp[i++]=make_pair(nums[cur1],index[cur1]);
                cur1++;
            }
        }
        while(cur1<=mid) {
            tmp[i++]=make_pair(nums[cur1],index[cur1]);
            cur1++;
        }

        while(cur2<=end){
            tmp[i++]=make_pair(nums[cur2],index[cur2]);
            cur2++;
        }

        for(int j=begin;j<=end;j++){
            nums[j]=tmp[j].first;
            index[j]=tmp[j].second;
        }
    }
public:
    vector<int> countSmaller(vector<int>& nums) {
        int n=nums.size();
        ret.resize(n);
        index.resize(n);
        for(int i=0;i<n;i++){
            index[i]=i;
        }
        tmp.resize(n);
        merge_sort(nums,0,n-1);
        return ret;
    }
private: 
    vector<int> ret;
    vector<int> index;
    vector<pair<int,int>> tmp;
};